<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\api\controller;


use cmf\controller\RestBaseController;
use think\response\Json;

//use AesHelper;

class LianlianController extends RestBaseController
{
    public $is_test = false;
    private $config;
    private $channelId = "1557";// 秘钥，用于生成签名
    private $sysSecret = "NjLVut5e0OO2OEXEnyszcA==";
    private $Aeckey = "YcDHcS/HkIImAqB6KYTdZg==";
    private $pBaseUrl = "http://jianguang.sdrcwl.com/api/api/";
    // 测试环境域名
    private $tbaseUrl = 'http://lianlian.free.idcfengye.com/ll/api/';

// 推送内容加密秘钥
    private $desAccesskey;
    private $signstr;

    public function __construct($config = [])
    {
        $this->config = $config;
    }

    protected function generateSign($encryptedData, $timestamp)
    {
        return md5($encryptedData . $this->channelId . $timestamp);
    }

    public function getAecKey()
    {
        return $this->Aeckey;
    }

    function httpRequest($url, $data = '', $method = 'GET')
    {
        var_dump($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
//        $headers[] = "Accept:application/json; charset= UTF-8";
//        if (!empty($headers)) {
//            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//        }
        //设置Header头
        $header[] = "Accept: application/json";
        $header[] = "Accept-Encoding: gzip";
//添加HTTP header头采用压缩和GET方式请求
        curl_setopt( $curl, CURLOPT_HTTPHEADER, $header );
        curl_setopt($curl,CURLOPT_ENCODING , "gzip");
//        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
//        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public function curl($url, $postFields = null)
    {
        var_dump($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "top-sdk-php"); // https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $headers[] = "Accept:application/json; charset= UTF-8";
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if (is_array($postFields) && 0 < count($postFields)) {
            $header = array("content-type: application/json; charset= UTF-8");
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
            json_encode($postFields);
        }
        $reponse = curl_exec($ch);
        var_dump($reponse);
        if (curl_errno($ch)) {
//            throw new UnprocessableEntityHttpException(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
//                throw new UnprocessableEntityHttpException($reponse, $httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }

    public function send()
    {
        $param['method'] = 'Lianliankk/lianlianindex';
        $param['params']['indx'] = 1;
        // 获取业务参数
        $apiParams = $param['params'];
        $method = $param['method'];
        if ($this->is_test) {
            $requestUrl = $this->tbaseUrl . $method . "?";
        } else {
            $requestUrl = $this->pBaseUrl . $method . "?";
        }
//        var_dump($apiParams);
//        exit();
        $encryptedData = AesHelper::encrypt(json_encode($apiParams), $this->Aeckey);
        var_dump($encryptedData);
        $sysParams['encryptedData'] = $encryptedData;
        $sysParams['channelId'] = $this->channelId;
        $sysParams['timestamp'] = intval(microtime(true) * 1000);
        $sysParams["sign"] = $this->generateSign($sysParams['encryptedData'], $sysParams['timestamp']);
        var_dump($sysParams);
        $resp = $this->httpRequest($requestUrl, $sysParams, 'POST');

//        $resp = $this->curl($requestUrl, $sysParams);
        var_dump($requestUrl);
        var_dump($resp);
        $re = json_decode($resp, true);
        if (($re['code'] == 200) && !empty($re['data'])) {
            p($re['data']);
            $re['result'] = AesHelper::decrypt($re['data']['encrypted Data'], $this->Aeckey);
            p($re['result']);
        }
    }

    protected function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
}

class AesHelper
{
    /*** 加密 * @param String input 加密的字符串 * @param String key 解密的 key * @return HexString */
    public static function encrypt($data, $key)
    {
        $data = openssl_encrypt($data, 'AES-128-ECB', base64_decode($key), OPENSSL_RAW_DATA);
        return base64_encode($data);
    }

    public static function decrypt($data, $key)
    {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'AES-128-ECB', base64_decode($key), OPENSSL_RAW_DATA);
    }

    public static function getMode($key)
    {
        if (strlen($key) === 32) {
            $mode = 'AES-256-ECB';
        } elseif (strlen($key) === 24) {
            $mode = 'AES-192-ECB';
        } else {
            $mode = 'AES-128-ECB';
        }
        return $mode;
    }
}
